#include "StatusServiceImpl.h"
#include <grpc++/grpc++.h>
#include <string>
#include "ConfigMgr.h"
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <memory>
#include <signal.h>


std::condition_variable cond;
std::mutex mtx;
bool b_stop = false;
std::unique_ptr<grpc::Server> server;


void RunServer()
{
    auto& cfg = ConfigMgr::GetInstance();
    std::string server_address = cfg["StatusServer"]["Host"]+":"+cfg["StatusServer"]["Port"];
    StatusServiceImpl service;
    grpc::ServerBuilder builder;
    builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
    
    builder.RegisterService(&service);
    

    server = builder.BuildAndStart();
    std::cout<<"StatusServer listening on "<<server_address<<std::endl;
    server->Wait();
}

void sigHandler(int signo)
{
    std::unique_lock<std::mutex> lock(mtx);
    b_stop = true;
    std::cout<<"signal "<<signo<<" received,exit..."<<std::endl;
    cond.notify_all();
}

int main()
{

    std::thread statusServerThread(RunServer);

    signal(SIGINT,sigHandler);
    signal(SIGTERM,sigHandler);

    std::unique_lock<std::mutex> lock(mtx);
    cond.wait(lock,[&](){return b_stop;});
    server->Shutdown();
    statusServerThread.join();

    return 0;
}